package cn.fresh.xuanyuan.module.trade.service.strategy;

import cn.fresh.xuanyuan.framework.common.util.wx.WxUtil;
import cn.fresh.xuanyuan.framework.common.util.date.DateUtils;
import cn.fresh.xuanyuan.module.pay.api.order.PayOrderApi;
import cn.fresh.xuanyuan.module.pay.api.order.dto.PayOrderDto;
import cn.fresh.xuanyuan.module.system.api.social.SocialClientApi;
import cn.fresh.xuanyuan.module.system.api.social.SocialUserApi;
import cn.fresh.xuanyuan.module.system.api.social.dto.SocialUserRespDTO;
import cn.fresh.xuanyuan.module.system.enums.social.SocialTypeEnum;
import cn.fresh.xuanyuan.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.fresh.xuanyuan.module.trade.dal.dataobject.order.TradeOrderItemDO;
import cn.fresh.xuanyuan.module.trade.dal.mysql.order.TradeOrderItemMapper;
import cn.fresh.xuanyuan.module.trade.enums.order.DouYinOrderStatusEnum;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("douYinSyncOrderStatusStrategy")
@Slf4j
public class DouYinSyncOrderStatusStrategy implements SyncOrderStatusStrategy {

    @Resource
    private PayOrderApi payOrderApi;

    @Resource
    private SocialUserApi socialUserApi;

    @Resource
    private SocialClientApi socialClientApi;

    @Resource
    private TradeOrderItemMapper tradeOrderItemMapper;

    @Override
    public void push(TradeOrderDO order, List<TradeOrderItemDO> itemList,PayOrderDto payOrderDto) {
        try {
            SocialUserRespDTO user = socialUserApi.getSocialUserByUserId(1, order.getUserId(), SocialTypeEnum.DOUYIN_MINI_APP.getType()).getCheckedData();
            String appId = payOrderApi.getPayAppId(String.valueOf(order.getId())).getCheckedData();
            if(StringUtils.isNotBlank(appId) && user != null && payOrderDto != null) {
                String accessToken = socialClientApi.getAccessToken(appId).getCheckedData();
                Map<String, Object> params = buildParams(user.getOpenid(),accessToken, order,  itemList, payOrderDto.getChannelOrderNo());
                String res = WxUtil.douYinPush(params);
                log.info("DouYinSyncOrderStatusStrategy res: {}", res);
                if(StringUtils.isNotBlank(res)) {
                    JSONObject json = JSONArray.parseObject(res);
                    if(json.getIntValue("err_code") == 0 && "success".equalsIgnoreCase(json.getString("err_msg"))) {
                        for(TradeOrderItemDO item : itemList) {
                            tradeOrderItemMapper.updateUploadWx(item.getId());
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            log.error("DouYinSyncOrderStatusStrategy push exception:", e);
        }
    }

    private Map<String, Object> buildParams(String openId,String accessToken,TradeOrderDO order, List<TradeOrderItemDO> itemList, String channelPayNo) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("app_name", "douyin");
        params.put("open_id", openId);
        JSONObject json = new JSONObject();
        json.put("order_id", channelPayNo);
        Date date = DateUtils.parseDate(order.getCreateTime());
        json.put("create_time", date.getTime());
        json.put("status", DouYinOrderStatusEnum.getDouYinStatusStr(order.getStatus()));
        json.put("amount", itemList.size());
        json.put("total_price", order.getPayPrice());
        String pageUrl = "pages/mail/order-detail?id=" + order.getId();
        json.put("detail_url", pageUrl);
        JSONArray list = new JSONArray();
        for(TradeOrderItemDO itemDO : itemList) {
            JSONObject item = new JSONObject();
            item.put("item_code", itemDO.getSpuId());
            item.put("img", itemDO.getPicUrl());
            item.put("title", itemDO.getSpuName());
            item.put("amount", itemDO.getCount());
            item.put("price", itemDO.getPayPrice());
            list.add(item);
        }
        json.put("item_list", list);
        params.put("order_detail", json.toJSONString());
        params.put("order_status", DouYinOrderStatusEnum.getDouYinStatusInt(order.getStatus()));
        params.put("order_type", 0);
        Date now = new Date();
        params.put("update_time", now.getTime() / 1000);
        return params;
    }
}
